<template>
  <div>
    <!-- 1.远程操控弹窗 -->
    <el-dialog
      title="远程控制"
      :visible.sync="controlVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      max-width="920px"
      min-width="600px"
      custom-class="remote-control lizhi"
      @close="resetControlList"
      append-to-body
      center
    >
      <div
        @click="dialogClick"
        class="clearfix"
        v-if="secondListFirst.length > 0"
      >
        <div class="everyLeft">
          <div
            class="everyOne"
            v-for="item in secondListFirst"
            :key="item.id"
            @click="controlClick(item)"
          >
            <h6>{{ item.commandDesc }}</h6>
            <div class="leftTop-wrapper">
              <div class="leftTop">
                <i
                  class="iconfont"
                  :class="{
                    'icon-guanbi': item.iconType === '1',
                    'icon-kaiqi': item.iconType === '2' || !item.iconType,
                    'icon-xiaoyin': item.iconType === '3',
                    'icon-chaxun': item.iconType === '4',
                    'icon-peizhi': item.iconType === '5',
                    green: item.iconState == 1 || !item.iconState,
                    red: item.iconState == 2,
                    normal: item.iconState == 3
                  }"
                ></i>
              </div>
            </div>
            <div class="leftText">
              操作指令:
              <span
                :class="{
                  blue: item.iconState == 1,
                  red: item.iconState == 2,
                  normal: item.iconState == 3 || !item.iconState
                }"
              >
                {{ ' ' + (item.aliasName || item.commandName) }}
              </span>
            </div>
          </div>
        </div>
        <div class="rightBox">
          <div class="titleR">远程操控授权剩余次数：{{ orderNum }}（次）</div>
          <div
            class="infinite-list-wrapper alarmListDialog"
          >
            <ul
              class="infinite-list-content"
              v-infinite-scroll="loadMore"
              infinite-scroll-disabled="disabledScroll"
              :infinite-scroll-delay="300"
              :infinite-scroll-immediate="false"
              :infinite-scroll-immediate-check="false"
              :infinite-scroll-distance="20"
            >
              <el-timeline>
                <el-timeline-item
                  color="#50E3C2"
                  v-for="(activity, index) in activities"
                  :key="index"
                >
                  <div class="everyOrderTitle">
                    <span>{{ activity.userName + ':' + activity.commandName }} </span>
                    <span>{{ activity.createTime }} </span>
                    <span v-if="activity.status == -1">指令执行未知</span>
                    <span
                      v-else-if="activity.status == 1"
                      style="color: #f84242"
                      >指令执行失败</span
                    >
                    <span v-else class="successStatus">指令执行成功</span>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </ul>
            <p v-if="loadingOrder">加载中...</p>
            <p v-if="noMore"></p>
          </div>
        </div>
      </div>
      <div class="no-control" v-else>
        <image src="../../static/img/no-alarm.png" alt="" />
        <div>暂无数据</div>
      </div>
    </el-dialog>

    <!--  2.发送验证码弹窗  -->
    <el-dialog
      title="确认操作"
      :visible.sync="smsDialogVisible"
      :before-close="cancelTimer"
      custom-class="send-sms-dialog lizhi"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="500px"
    >
      <el-tabs v-model="yzName" class="turing-tabs equipmtabs" type="card">
        <el-tab-pane label="验证码校验" name="yzm">
          <p class="sms-title">
            请输入<span>{{ userphone }}</span
            >的手机验证码：
          </p>
          <div class="dialog-sendsms">
            <el-input
              v-model.trim="phonecode"
              type="text"
              maxlength="10"
              placeholder="验证码"
            ></el-input>
            <el-button
              v-preventReClick
              size="small"
              type="primary"
              :disabled="isOvertime"
              @click="apiSendcode"
              >{{ phoneword }}</el-button
            >
          </div>
        </el-tab-pane>
        <el-tab-pane label="密码校验" name="password">
          <p class="sms-title">用户名：{{ username }}</p>
          <div class="dialog-sendsms">
            <el-input
              v-model="password"
              :type="passwordType"
              placeholder="请输入当前用户登录密码"
            >
              <i
                slot="suffix"
                class="el-input__icon icon-show1"
                :class="{ 'icon-show': showFlag }"
                @click="showPassword"
              />
            </el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSmsDialog">取 消</el-button>
        <el-button type="primary" @click="jpStatusDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!--  3.状态弹窗  -->
    <el-dialog
      title="操作执行状态"
      :visible.sync="statusDialogVisible"
      custom-class="status-sms-dialog lizhi"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      width="500px"
      @close="cancelReload"
    >
      <div class="dialog-timeline">
        <el-timeline>
          <el-timeline-item placement="top">
            操作任务正在执行中，请耐心等待....
          </el-timeline-item>
          <el-timeline-item v-if="statusObj" placement="top">
            {{ statusObj.createTime }} 发出操作指令
          </el-timeline-item>
          <el-timeline-item v-if="statusObj" placement="top">
            执行中，已等待：{{
              waitTime(statusObj.createTime, statusObj.updateTime)
            }}
          </el-timeline-item>
          <el-timeline-item
            v-if="
              statusObj && (statusObj.status === 0 || statusObj.status === 2)
            "
            placement="top"
          >
            {{ statusObj.updateTime }} 指令执行成功
          </el-timeline-item>
          <el-timeline-item
            v-if="statusObj && statusObj.status === 1"
            placement="top"
          >
            {{ statusObj.updateTime }} 指令执行失败
          </el-timeline-item>
          <el-timeline-item
            v-if="statusObj && statusObj.status <= 0"
            placement="top"
          >
            当前状态：{{ statusObj.commandName }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelReload">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  reduceVerifyNum,
  sendCommand,
  queryStatus,
  verifyCommandSms,
  listDeviceModelNextCommand,
  sendCommandSms,
  getDeptSet,
  listDeviceCommandDesc,
  commadHistoryList,
  verifyPassword,
  resetVerifyNum
} from "../../api/equipManage.js";

import { encryption } from "../../util/util.js";

export default {
  name: "RemoteControl",
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 设备id
    deviceId: {
      default: null
    },
    // 单位id
    deptId: {
      type: Number,
      default: 0,
      require: true
    }
  },
  data() {
    return {
      controlList: [],
      popupFlag: true,
      isVerify: false,
      phonecode: "",
      isOvertime: false,
      phoneword: "获取验证码",
      smsDialogVisible: false,
      userInfo: {
        phone: ""
      },
      userphone: "",
      username: "",
      pageAlarm: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 15 // 每页显示多少条
      },
      activities: [],
      loading: false,
      activeName: "first",
      secondList: [],
      timeNum: 0,
      orderTimer: 0,
      controlVisible: false,
      orderDialogVisible: false,
      updateParams: {
        deviceModelCommandId: "" //操作指令名称
      },
      statusDialogVisible: false,
      statusObj: {
        status: 0
      },
      timer: 0,
      yzName: "yzm",
      passwordType: "password",
      showFlag: false,
      orderTitle: "",
      password: "",
      maxTime: 2 * 60,
      secondListFirst: [],
      orderNum: 0,
      loadingOrder: false,
      countTimer: null
    };
  },
  computed: {
    noMore() {
      //当起始页数大于总页数时停止加载
      return this.activities.length >= this.pageAlarm.total;
    }
  },
  watch: {
    // 当show变更时, if show为true,则初始化表单
    show: function (val) {
      if (val) {
        this.$nextTick(() => {
          this.remoteControl();
        });
      }
    }
  },
  methods: {
    /**
     * @description: 加载更多操作指令
     * @return {*}
     */
    loadMore() {
      this.loadingOrder = true;
      this.pageAlarm.currentPage++;
      this.getOrderList();
    },
    /**
     * @description: 1.打开远程控制弹窗并初始化数据
     * @return {*}
     */
    remoteControl() {
      this.dialogClick();
      this.getSecondList();
      this.getOrderList();
      this.getOrderNum();
      // 显示远程控制弹窗
      this.controlVisible = true;
    },
    /**
     * @description: 重置远程操作数据
     * @return {*}
     */
    resetControlList() {
      this.pageAlarm = {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 15 // 每页显示多少条
      };
      // 初始化远程控制数据
      this.isVerify = false;
      this.activities = [];
      this.loading = false;
      this.activeName = "first";
      this.secondList = [];

      // 清楚静默状态相关值
      this.timeNum = 0;
      if (this.orderTimer) {
        clearInterval(this.orderTimer);
        this.orderTimer = null;
      }

      // 关闭弹窗
      this.controlVisible = false;
      this.orderDialogVisible = false;
      this.$emit("update:show", false);
      this.$emit("closeRemoteControl");
    },
    /**
     * @description: 1-1.定时重置远程操作数据
     * @return {*}
     */
    dialogClick() {
      this.timeNum = 0;
      if (this.orderTimer) {
        clearInterval(this.orderTimer);
        this.orderTimer = null;
      }
      let that = this;
      that.orderTimer = setInterval(function () {
        this.timeNum++;
        if (that.timeNum > that.maxTime) {
          that.resetControlList();
        }
      }, 1000);
    },
    /**
     * @description: 1-2.获取操作指令列表
     * @return {*}
     */
    getSecondList() {
      listDeviceCommandDesc({
        deviceId: this.deviceId
      })
        .then((res) => {
          this.secondList = res.data;
          this.secondListFirst = res.data;
          console.log(res.data);
        })
        .catch(() => {});
    },
    /**
     * @description: 1-3.获取操作指令记录
     * @return {*}
     */
    getOrderList() {
      commadHistoryList(
        Object.assign({
          pageNum: this.pageAlarm.currentPage,
          pageSize: this.pageAlarm.pageSize,
          deviceId: this.deviceId
        })
      )
        .then((res) => {
          this.activities = this.activities.concat(res.data.list);
          this.pageAlarm.total = res.data.total;
          this.$nextTick(function () {
            this.loadingOrder = false;
          });
        })
        .catch(() => {
          this.loadingOrder = false;
        });
    },
    /**
     * @description: 1-4.获取操控次数
     * @return {*}
     */
    getOrderNum() {
      getDeptSet()
        .then((res) => {
          this.isVerify =
            res.data.isVerify === 1 && res.data.remainNum === 0
              ? true
              : false;
          console.log(res.data.isVerify);
          console.log(res.data.isVerify === 0);
          this.orderNum =
            res.data.isVerify === 0 || !res.data.totalNum
              ? "无限"
              : res.data.remainNum;
        })
        .catch(() => {});
    },
    /**
     * @description: 2.校验用户操作权限,防误触确认
     * @return {*}
     */
    controlClick(item) {
      this.commandType = item.commandType;
      this.updateParams.deviceModelCommandId = item.deviceModelCommandId;
      this.$confirm("确认进行远程操控吗?", "确认操作", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 如果需要验证
          if (this.isVerify) {
            this.resetControlList();
            // 发送验证码
            this.phonecode = "";
            this.isOvertime = false;
            this.phoneword = "获取验证码";
            // 打开验证弹窗
            this.smsDialogVisible = true;
            let orphone = this.userInfo.phone;
            let nwphone = orphone.substr(0, 3) + "****" + orphone.substr(7);
            this.userphone = nwphone;
            this.username = this.userInfo.username;
          } else {
            //如果不是自定义远程按钮
            if (item.commandType !== 1) {
              this.resetControlList();
              reduceVerifyNum({ deptId: this.deptId }).then((res) => {
                this.sendCommandChange();
              });
            } else {
              //如果是自定义远程按钮,则填写远程指令
              this.listDeviceModelNextCommandChange();
            }
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消远程操控"
          });
        });
    },
    /**
     * @description: 2-1-1.发送短信验证码
     * @return {*}
     */
    apiSendcode() {
      sendCommandSms(
        Object.assign(
          { deviceId: this.deviceId, userId: this.userInfo.userId },
          this.updateParams
        )
      )
        .then(function (response) {
          this.showcodetime();
          let res = response.data;
          if (res.code === 0 || res.msg === "发送成功") {
            this.$notify({
              title: "成功",
              message: "验证码已发送",
              type: "success",
              position: "bottom-right"
            });
          }
        })
        .catch(function (error) {
          this.$message({
            message: error.response.data.message,
            type: "warning"
          });
        });
    },
    /**
     * @description: 2-1-1-1.等待验证码倒计时
     * @return {*}
     */
    showcodetime() {
      if (this.isOvertime) {
        return false;
      }
        time = 60;
      this.isOvertime = true;
      this.countTimer = setInterval(function () {
        this.isOvertime = true;
        time--;
        this.phoneword = "已发送(" + time + "s)";
        if (time < 0) {
          this.isOvertime = false;
          clearInterval(this.countTimer);
          this.phoneword = "获取验证码";
        }
      }, 1000);
    },
    /**
     * @description: 2-1-2.显示密码
     * @return {*}
     */
    showPassword() {
      this.showFlag = !this.showFlag;
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    /**
     * @description: 2-1-3. 确认验证信息
     * @return {*}
     */
    jpStatusDialog() {
      // 验证通过后跳转到状态弹窗
      if (this.yzName === "yzm") {
        if (!this.phonecode) {
          this.$message.warning("请输入验证码");
        } else {
          // 验证
          verifyCommandSms(
            Object.assign(
              {
                deviceId: this.deviceId,
                userId: this.userInfo.userId,
                code: this.phonecode
              },
              this.updateParams
            )
          ).then((res) => {
            this.reduceVerifyNumChange("phone");
          });
        }
      } else {
        if (!this.password) {
          this.$message.warning("请输入密码");
        } else {
          // 验证
          let userInfo = {
            password: this.password
          };
          const user = encryption({
            data: userInfo,
            key: "pigxpigxpigxpigx",
            param: ["password"]
          });
          verifyPassword(
            Object.assign(
              {
                deviceId: this.deviceId,
                userId: this.userInfo.userId,
                password: user.password
              },
              this.updateParams
            )
          ).then((res) => {
            this.reduceVerifyNumChange("password");
          });
        }
      }
    },
    /**
     * @description:
     * @param {*} type: 2-1-4.验证短信效验码或用户密码是否正确,正确则发送控制指令
     * @return {*}
     */
    reduceVerifyNumChange(type) {
      resetVerifyNum({ deptId: this.deptId }).then((res) => {
        if (this.commandType !== 1) {
          reduceVerifyNum({ deptId: this.deptId }).then((res) => {
            if (type === "phone") {
              this.phonecode = "";
              this.phoneword = "获取验证码";
              this.userphone = "";
            } else {
              this.password = "";
              this.username = "";
            }
            this.cancelTimer();
            // 开启状态弹窗
            this.sendCommandChange();
          });
        } else {
          //如果是自定义远程按钮,则填写远程指令
          this.listDeviceModelNextCommandChange();
        }
      });
    },
    /**
     * @description: 2-1-5.关闭验证
     * @return {*}
     */
    closeSmsDialog() {
      //关闭弹窗，清空数据
      this.phonecode = "";
      this.phoneword = "获取验证码";
      this.userphone = "";
      this.password = "";
      this.username = "";
      this.cancelTimer();
    },
    /**
     * @description: 2-2-1.发送远程操控指令
     * @return {*}
     */
    sendCommandChange() {
      // 开启状态弹窗
      sendCommand(
        Object.assign({ deviceId: this.deviceId }, this.updateParams)
      ).then((res) => {
        this.statusDialogVisible = true;
        this.$message({
          type: "success",
          message: "远程操控指令发送成功!"
        });
        // 轮询获取状态
        this.getStatus(res.data);
        this.timer = window.setInterval(() => {
          setTimeout(() => {
            this.getStatus(res.data);
          }, 1);
        }, 5000);
      });
    },
    /**
     * @description: 2-2-2.获取设备状态
     * @param {*} randcode
     * @return {*}
     */
    getStatus(randcode) {
      queryStatus({ messageLogId: randcode }).then((res) => {
        this.statusObj = {};
        this.statusObj = res.data;
        if (this.statusObj && this.statusObj.status > 0) {
          // 成功则清除定时器
          clearInterval(this.timer);
        }
      });
    },
    /**
     * @description: 2-2-3.计算时间差
     * @param { Date } ptime:开始时间
     * @param { Date } ntime:结束时间
     * @return { String } 等待时间
     */
    waitTime(ptime, ntime) {
      const d = new Date(ptime).getTime();
      const u = new Date(ntime).getTime();
      // const diff = (u - d) / 1000
      let theTime = (u - d) / 1000; // 秒
      let middle = 0; // 分
      let hour = 0; // 小时

      if (theTime > 60) {
        middle = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (middle > 60) {
          hour = parseInt(middle / 60);
          middle = parseInt(middle % 60);
        }
      }
      let result = "" + parseInt(theTime) + "秒";
      if (middle > 0) {
        result = "" + parseInt(middle) + "分" + result;
      }
      if (hour > 0) {
        result = "" + parseInt(hour) + "小时" + result;
      }
      return result;
    },
    /**
     * @description: 2-2-4.取消等待,关闭等待窗
     * @return {*}
     */
    cancelReload() {
      clearInterval(this.timer);
      this.statusDialogVisible = false;
    },
    /**
     * @description: 自定义指令事件
     * @return {*}
     */
    listDeviceModelNextCommandChange() {
      this.$message({
        message: "暂不支持自定义指令!",
        type: "error"
      })
    },
    /**
     * @description: 清除定时器并关闭验证弹窗
     * @return {*}
     */
    cancelTimer() {
      clearInterval(this.timer);
      clearInterval(this.countTimer);
      this.smsDialogVisible = false;
    }
  }
};
</script>

<style lang="scss">

.no-control {
  margin-top: 10px;
  width: 100%;
  background: #011425;
  opacity: 0.8;
  color: rgba(255, 255, 255, 0.7);
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 230px;
  uni-image {
    width: 132px;
    height: 97px;
  }
}
.everyLeft {
  width: 68%;
  float: left;
}
.everyOne {
  width: 30%;
  float: left;
  margin-right: 3.3%;
  margin-bottom: 10px;
  cursor: pointer;
  font-size: 0.18rem;
  color: #ccd0d3;
  h6 {
    line-height: 30px;
    font-size: 0.2rem;
	height: 0.375rem;
  }
  .leftTop-wrapper {
    width: 2.06rem;
    height: 1.36rem;
    border-radius: 8px;
    border: 1px solid #04536b;
    background: #011425;
    padding: 2px;
  }
}
.leftTop {
  width: 100%;
  height: 100%;
  background: linear-gradient(180deg, #003353 0%, #062139 100%);
  border-radius: 8px;
  border: 1px solid #3de5ff31;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.leftTop i {
  font-size: 0.43rem !important;
  display: block;
  height: 0.43rem;
}
.blue {
  color: #02c3ff;
}
.red {
  color: #ff6868;
}
.normal {
  color: #999;
}

.leftTop p {
  color: rgba(255, 255, 255, 0.3);
  font-size: 12px;
  text-align: center;
  line-height: 18px;
}
.leftText {
  width: 100%;
  line-height: 40px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #fff;
}
.clearfix::after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}
.rightBox {
  width: 32%;
  float: right;
  background: rgba(0, 0, 0, 0.3);
  padding: 15px 0 15px 15px;
  .alarmListDialog{
    .infinite-list-content {
      min-height: 120px;
      padding: 0;
      max-height: 380px;
      overflow-y: auto;
      .everyOrderTitle{
        line-height: 20px;
        color: #aaa;
        span {
          margin-right: 10px;
        }
        .successStatus {
          color: #02c3ff;
        }
      }
      .el-timeline {
        padding: 0;
        .el-timeline-item{
          padding: 5px 0;
        }
        .el-timeline-item__tail{
          left: 10px;
        }
        .el-timeline-item__node--large{
          left: 4px;
        }
        .el-timeline-item__node--normal{
          left: 6px;
          width: 8px;
          height: 8px;
        }
        .el-timeline-item__wrapper{
          padding-left: 10px;
        }
        .el-timeline-item__timestamp.is-top{
          padding-top: 0;
          color: #ddd;
        }
      }
    }
  }
}
.titleR {
  line-height: 40px;
  color: #fff;
}
.order-sms-dialog {
  max-height: 600px;
  overflow-y: auto;
  p {
    color: rgba(255, 255, 255, 0.7);
    line-height: 25px;
  }
}
</style>